﻿using DllDependenciesAnalysis.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DllDependenciesAnalysis.DllAutoCompletions.Business
{
    public class RemoteNugetAutoCompletion : IAutoCompletion
    {
        public string NugetDir { get; set; }

        public MatchingStrategy MatchingStrategy { get; set; }

        public NugetRuntime[] NugetRuntimes { get; set; }

        public RemoteNugetAutoCompletion(string path, MatchingStrategy matching, params string[] urls)
        {
            NugetDir = path;
            MatchingStrategy = matching;

            if (urls?.Any() == true)
            {
                NugetRuntimes = urls.Select(n => new NugetRuntime(n)).ToArray();
            }
        }

        public bool Completion(string path, string name, Version version)
        {
            if (NugetRuntimes?.Any() != true)
                return false;

            CancellationToken token = new CancellationToken();

            var matchVersions = new List<DownloadPakcageResult>();

            foreach (var runtime in NugetRuntimes)
            {
                var result = NugetHelper.TryDownloadPackage(runtime, name, version, MatchingStrategy, token);

                if (result.Success)
                    matchVersions.Add(result);
            }

            if (matchVersions?.Any() != true)
                return false;

            DownloadPakcageResult mustMatchVersion = null;

            if (IsUseLatestVersion())
            {
                mustMatchVersion = matchVersions.OrderByDescending(n => n.MatchVersion.GetLongHashCode()).First();
            }
            else
            {
                mustMatchVersion = matchVersions.OrderBy(n => n.MatchVersion.GetLongHashCode()).First();
            }

            // 移动相关的文件
            return NugetHelper.CopyNugetPackageFiles(NugetDir, name, mustMatchVersion.MatchVersion, path);
        }

        public bool IsUseLatestVersion()
        {
            if (MatchingStrategy == MatchingStrategy.Latest)
                return true;

            return false;
        }
    }
}
